import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'

// 配置dayjs
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

/**
 * 格式化时间为相对时间
 */
export function formatRelativeTime(timestamp: number): string {
  return dayjs(timestamp).fromNow()
}

/**
 * 格式化时间为具体日期
 */
export function formatDateTime(timestamp: number, format = 'YYYY-MM-DD HH:mm'): string {
  return dayjs(timestamp).format(format)
}

/**
 * 格式化数字（添加千分位分隔符）
 */
export function formatNumber(num: number): string {
  if (num >= 100000) {
    return (num / 10000).toFixed(1) + 'w'
  } else if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toLocaleString()
}

/**
 * 生成随机颜色
 */
export function getRandomColor(): string {
  const colors = [
    '#00d4ff', '#39ff14', '#ff6b35', '#8b5cf6', 
    '#f59e0b', '#ef4444', '#10b981', '#f97316'
  ]
  return colors[Math.floor(Math.random() * colors.length)]
}

/**
 * 截取文本并添加省略号
 */
export function truncateText(text: string, maxLength: number): string {
  if (text.length <= maxLength) {
    return text
  }
  return text.substring(0, maxLength) + '...'
}

/**
 * 防抖函数
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: ReturnType<typeof setTimeout>
  return function(this: any, ...args: Parameters<T>) {
    clearTimeout(timeout)
    timeout = setTimeout(() => func.apply(this, args), wait)
  }
}

/**
 * 节流函数
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let lastFunc: ReturnType<typeof setTimeout>
  let lastRan: number
  return function(this: any, ...args: Parameters<T>) {
    if (!lastRan) {
      func.apply(this, args)
      lastRan = Date.now()
    } else {
      clearTimeout(lastFunc)
      lastFunc = setTimeout(() => {
        if (Date.now() - lastRan >= limit) {
          func.apply(this, args)
          lastRan = Date.now()
        }
      }, limit - (Date.now() - lastRan))
    }
  }
}

/**
 * 获取分类对应的图标
 */
export function getCategoryIcon(category: string): string {
  const iconMap: Record<string, string> = {
    'AI': 'cpu',
    'Blockchain': 'connection',
    'Hardware': 'monitor',
    'Startup': 'trend-charts',
    'Mobile': 'iphone'
  }
  return iconMap[category] || 'document'
}

/**
 * 获取分类对应的颜色
 */
export function getCategoryColor(category: string): string {
  const colorMap: Record<string, string> = {
    'AI': '#00d4ff',
    'Blockchain': '#39ff14',
    'Hardware': '#ff6b35',
    'Startup': '#8b5cf6',
    'Mobile': '#f59e0b'
  }
  return colorMap[category] || '#666666'
}

/**
 * 获取优先级对应的标签样式
 */
export function getPriorityStyle(priority: string): { type: string; text: string } {
  const priorityMap: Record<string, { type: string; text: string }> = {
    'breaking': { type: 'danger', text: '突发' },
    'featured': { type: 'warning', text: '精选' },
    'hot': { type: 'success', text: '热门' },
    'normal': { type: 'info', text: '普通' }
  }
  return priorityMap[priority] || { type: 'info', text: '普通' }
}

/**
 * 滚动到顶部
 */
export function scrollToTop(smooth = true): void {
  window.scrollTo({
    top: 0,
    behavior: smooth ? 'smooth' : 'auto'
  })
}

/**
 * 复制文本到剪贴板
 */
export async function copyToClipboard(text: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(text)
    return true
  } catch (error) {
    console.error('复制失败:', error)
    return false
  }
}

/**
 * 生成随机ID
 */
export function generateId(): string {
  return Math.random().toString(36).substring(2) + Date.now().toString(36)
}

/**
 * 检查是否为移动设备
 */
export function isMobile(): boolean {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}